#include "RenderDevice.h"

#include <d3dx9.h>
#include <sstream>
#include <string>

//////////////////////////////////////////////////
//RenderDevice
//////////////////////////////////////////////////

//------------------------------------------------

RenderDevice::RenderDevice(void)
  {
  }

//------------------------------------------------

RenderDevice::~RenderDevice(void)
  {
  if(m_d3d_device)
    {
    m_d3d_device->Release();
    m_d3d_device = NULL;
    }
  if(m_font)
    {
    m_font->Release();
    m_font = NULL;
    }    
  }

//------------------------------------------------

bool RenderDevice::Init(HWND ih_window)
  {
	IDirect3D9* d3d9 = Direct3DCreate9(D3D_SDK_VERSION); 

  if(!d3d9)
    {
		::MessageBox(0, "Direct3DCreate9() - FAILED", 0, 0);
		return false;
	  }	

	D3DCAPS9 caps;
	d3d9->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &caps);

	int vp = 0;
	if(caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
    {
		vp = D3DCREATE_HARDWARE_VERTEXPROCESSING;    
    }
	else
    {
		vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
    }
 
	D3DPRESENT_PARAMETERS d3dpp;
	d3dpp.BackBufferWidth            = 800;
	d3dpp.BackBufferHeight           = 600;
	d3dpp.BackBufferFormat           = D3DFMT_X8R8G8B8;
	d3dpp.BackBufferCount            = 1;
	d3dpp.MultiSampleType            = D3DMULTISAMPLE_NONE;
	d3dpp.MultiSampleQuality         = 0;
	d3dpp.SwapEffect                 = D3DSWAPEFFECT_DISCARD; 
	d3dpp.hDeviceWindow              = ih_window;
	d3dpp.Windowed                   = true;
	d3dpp.EnableAutoDepthStencil     = true; 
	d3dpp.AutoDepthStencilFormat     = D3DFMT_D24S8;
	d3dpp.Flags                      = 0;
	d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
	d3dpp.PresentationInterval       = D3DPRESENT_INTERVAL_IMMEDIATE;

	if(FAILED(d3d9->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, ih_window, vp, &d3dpp, &m_d3d_device)))
    {	
		d3d9->Release();
		::MessageBox(0, "CreateDevice() - FAILED", 0, 0);
		return false;
    }

	d3d9->Release();

  if(FAILED(D3DXCreateFont(m_d3d_device, 22, 0, FW_NORMAL, 1, false, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH|FF_DONTCARE, "Arial", &m_font)))
    {
    ::MessageBox(0, "CreateFont() - FAILED", 0, 0);
    return false;
    } 

	return true;
  }

//------------------------------------------------

IDirect3DDevice9* RenderDevice::GetDirect3DDevice() const
  {
  return m_d3d_device;
  }

//------------------------------------------------

void RenderDevice::ShowFPS(int i_fps)
  {
  std::stringstream inputstream;
  inputstream << i_fps;  
  RECT font_rect;
  SetRect(&font_rect,0,0,100,100);  
  m_font->DrawText(NULL, inputstream.str().c_str(), -1, &font_rect, DT_LEFT, 0xFFFF0000);  
  }

//------------------------------------------------

//////////////////////////////////////////////////